package com.example.base.excetion;

import com.alibaba.fastjson.JSONObject;
import com.example.base.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@ControllerAdvice
@Slf4j
public class ExcetionConfig {

    /**
     * 校验组件使用
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public JSONObject serviceHandle(MethodArgumentNotValidException e) {
        log.info("有异常");
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(allErrors.get(0).getDefaultMessage());
        log.info(stringBuilder.toString());
        return Result.errorInfo(stringBuilder.toString());
    }


    @ExceptionHandler(value = GlobalExcetion.class)
    @ResponseBody
    public JSONObject serviceHandle(GlobalExcetion e) {
        log.info("异常信息异常码: {} 自定义异常信息:{} 系统异常信息:{}",e.getCode(),e.getMsg(),e.getMessage());
        return Result.msg(e.getCode(),e.getMsg());
    }

}
